<?php

/**
 * @author gbfun <gbfun@163.com>  2018-05-28 16:21
 * http://www.wuweiyou.com
 */

class wwy_image_handler
{ 
    protected static $_instance = null;
    
    private function __clone()
    {
    }
    
    /**
     * @return wwy_image_handler
     */
    public static function get_instance()
    {
        if (null === self::$_instance) {
            self::$_instance = new self();    //by gbfun 又是静态变量
        }
    
        return self::$_instance;
    }
    
    protected function __construct()
    {
        
    }
    
    public function mk_thumb($origin, $width, $height, $target, $ext = 'jpg')
    {  	
    	$origin_info = @getimagesize($origin);
    	$origin      = $this->img_resource($origin, $origin_info[2]);
    	
        //图片比例、大小、背景色
        $scale      = $origin_info[0] / $origin_info[1];
        if ($width == 0) {
            $width = $height * $scale;
        }
        if ($height == 0) {
            $height = $width / $scale;
        }
    	$thumb = imagecreatetruecolor($width, $height);    	    	
    	$white = imagecolorallocate($thumb, 255, 255, 255);  
    	imagefilledrectangle($thumb, 0, 0, $width, $height, $white); 

    	//把原图缩放、贴到新建图片上
    	if ($origin_info[0] / $width > $origin_info[1] / $height) {
            /* 原始图片比较宽，则以宽度为准 */
    		$dst_w = $width;
            $dst_h = $width / $scale;
        } else {
            /* 原始图片比较高，则以高度为准 */            
            $dst_w = $height * $scale;
            $dst_h = $height;
        }
        $dst_x = ($width  - $dst_w) / 2;
        $dst_y = ($height - $dst_h) / 2;
        imagecopyresampled($thumb, $origin, $dst_x, $dst_y, 0, 0, $dst_w, $dst_h, $origin_info[0], $origin_info[1]);
        
    	/* 生成文件 */
        $function_lookup = array('jpg' => 'jpeg', 'gif' => 'gif', 'png' => 'png');
        if (!empty($function_lookup[$ext])) {
        	$function = 'image' . $function_lookup[$ext];
        	$function($thumb, $target);        	
        }else{
        	return false;
        } 
    	
    	imagedestroy($thumb);
        imagedestroy($origin);
    }
    
	function img_resource($origin, $mimeType)
    {
        switch ($mimeType)
        {
            case 1:
            case 'image/gif':
                $res = imagecreatefromgif($origin);
                break;

            case 2:
            case 'image/pjpeg':
            case 'image/jpeg':
                $res = imagecreatefromjpeg($origin);
                break;

            case 3:
            case 'image/x-png':
            case 'image/png':
                $res = imagecreatefrompng($origin);
                break;

            default:
                return false;
        }

        return $res;
    }
}
